package com.sddnytsh.body_buildingsystem.screens

import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.filled.Reply
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.sddnytsh.body_buildingsystem.config.NetworkConfig
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.network.CommunityApiService
import com.sddnytsh.body_buildingsystem.topic.CommunityPost
import com.sddnytsh.body_buildingsystem.topic.Comment
import com.sddnytsh.body_buildingsystem.utils.navigateCommentDetail
import com.sddnytsh.body_buildingsystem.components.CommentItem
import com.sddnytsh.body_buildingsystem.components.CommentReplyWindow
import com.sddnytsh.body_buildingsystem.components.SimpleAvatarImage
import com.sddnytsh.body_buildingsystem.components.DefaultAvatar
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

// API响应数据类
data class CommentAddResponse(val success: Boolean, val message: String? = null)

// 获取评论列表的函数
suspend fun getCommentsByPostId(postId: Int, currentUserId: Long? = null): List<Comment> {
    data class CommentApiResponse<T>(
        val success: Boolean,
        val data: T
    )
    
    data class NestedData(
        val comments: List<Map<String, Any>>
    )

    return withContext(Dispatchers.IO) {
        val url = if (currentUserId != null) {
            "${NetworkConfig.BASE_URL}/api/post-comments/post/$postId?currentUserId=$currentUserId"
        } else {
            "${NetworkConfig.BASE_URL}/api/post-comments/post/$postId"
        }

        val client = OkHttpClient.Builder()
            .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .readTimeout(8, java.util.concurrent.TimeUnit.SECONDS)
            .writeTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .connectionPool(okhttp3.ConnectionPool(5, 5, java.util.concurrent.TimeUnit.MINUTES))
            .build()
        val request = Request.Builder()
            .url(url)
            .build()

        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) {
                throw IOException("Unexpected code $response")
            }

            val responseBody = response.body?.string()
            val gson = Gson()
            val apiResp: CommentApiResponse<NestedData> = gson.fromJson(
                responseBody,
                object : TypeToken<CommentApiResponse<NestedData>>() {}.type
            )
            if (apiResp.success) {
                // 将Map转换为Comment对象
                apiResp.data.comments.map { commentMap ->
                    Comment(
                        id = (commentMap["id"] as? Number)?.toLong() ?: 0L,
                        postId = (commentMap["postId"] as? Number)?.toLong() ?: 0L,
                        userId = (commentMap["userId"] as? Number)?.toLong() ?: 0L,
                        content = commentMap["content"] as? String ?: "",
                        likeCount = (commentMap["likeCount"] as? Number)?.toInt() ?: 0,
                        isLiked = commentMap["isLiked"] as? Boolean ?: false,
                        createdAt = commentMap["createdAt"] as? String ?: "",
                        author = commentMap["author"] as? String ?: "匿名用户",
                        authorAvatar = commentMap["authorAvatar"] as? String, // 🔥 添加作者头像字段
                        parentId = (commentMap["parentId"] as? Number)?.toLong(),
                        rootId = (commentMap["rootId"] as? Number)?.toLong(),
                        isDeleted = commentMap["isDeleted"] as? Boolean ?: false
                    )
                }
            } else {
                emptyList()
            }
        }
    }
}

// 发送评论的函数 - 优化性能
suspend fun addComment(postId: Int, content: String, userId: Long, parentId: Long? = null, rootId: Long? = null): CommentAddResponse {
    data class CommentRequest(
        val postId: Long,
        val userId: Long,
        val content: String,
        val parentId: Long? = null,
        val rootId: Long? = null
    )

    return withContext(Dispatchers.IO) {
        val url = "${NetworkConfig.BASE_URL}/api/post-comments"

        // 创建请求体
        val commentRequest = CommentRequest(postId.toLong(), userId, content, parentId, rootId)
        val gson = Gson()
        val requestBody = gson.toJson(commentRequest).toRequestBody("application/json".toMediaType())

        // 🔥 优化网络配置 - 减少超时时间，提高响应速度
        val client = OkHttpClient.Builder()
            .connectTimeout(3, java.util.concurrent.TimeUnit.SECONDS)
            .readTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
            .writeTimeout(3, java.util.concurrent.TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .connectionPool(okhttp3.ConnectionPool(5, 5, java.util.concurrent.TimeUnit.MINUTES))
            .build()
            
        val request = Request.Builder()
            .url(url)
            .post(requestBody)
            .addHeader("Content-Type", "application/json")
            .build()

        try {
            Log.d("PostDetailScreen", "🔥 开始发送评论，postId: $postId, content: $content")
            client.newCall(request).execute().use { response ->
                if (!response.isSuccessful) {
                    Log.e("PostDetailScreen", "🔥 评论发送失败: ${response.code}")
                    throw IOException("Unexpected code $response")
                }

                val responseBody = response.body?.string()
                val result = gson.fromJson(responseBody, CommentAddResponse::class.java)
                Log.d("PostDetailScreen", "🔥 评论发送成功")
                result
            }
        } catch (e: Exception) {
            Log.e("PostDetailScreen", "🔥 评论发送异常: ${e.message}")
            throw e
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PostDetailScreen(navController: NavController, postId: Int) {
    val context = LocalContext.current
    // 状态管理
    var post by remember { mutableStateOf<CommunityPost?>(null) }
    var comments by remember { mutableStateOf<List<Comment>>(emptyList()) }
    var isLoading by remember { mutableStateOf(true) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    
    // 评论输入相关状态
    var showCommentInput by remember { mutableStateOf(false) }
    var newComment by remember { mutableStateOf("") }
    var isSubmittingComment by remember { mutableStateOf(false) }
    
    // 回复窗口相关状态
    var showReplyWindow by remember { mutableStateOf(false) }
    var selectedComment by remember { mutableStateOf<Comment?>(null) }
    
    // 防抖机制 - 防止重复导航
    var lastNavigationTime by remember { mutableStateOf(0L) }
    
    val coroutineScope = rememberCoroutineScope()
    val communityApiService = remember { CommunityApiService() }
    
    // 🔥 添加缓存机制 - 避免重复加载
    var hasLoaded by remember { mutableStateOf(false) }
    var lastLoadTime by remember { mutableStateOf(0L) }
    val CACHE_DURATION = 120000L // 120秒缓存，减少重复请求

    // 从API获取帖子详情和评论
    LaunchedEffect(postId) {
        // 🔥 检查缓存 - 避免重复加载
        val currentTime = System.currentTimeMillis()
        if (hasLoaded && (currentTime - lastLoadTime) < CACHE_DURATION) {
            Log.d("PostDetailScreen", "🔥 使用缓存数据，跳过网络请求")
            isLoading = false
            return@LaunchedEffect
        }
        
        isLoading = true
        errorMessage = null

        try {
            Log.d("PostDetailScreen", "🔥 开始加载帖子详情，postId: $postId")
            val currentUserId = UserState.currentUserId
            val postsResult = communityApiService.getAllPosts(currentUserId)
            if (postsResult.isSuccess) {
                val allPosts = postsResult.getOrNull() ?: emptyList()
                val targetPost = allPosts.find { it.id == postId.toLong() }
                
                if (targetPost != null) {
                    post = targetPost
                    val commentsResult = getCommentsByPostId(postId, currentUserId)
                    comments = commentsResult
                    hasLoaded = true
                    lastLoadTime = currentTime
                    Log.d("PostDetailScreen", "🔥 帖子详情加载完成")
                } else {
                    errorMessage = "帖子不存在或已被删除"
                }
            } else {
                errorMessage = "获取帖子失败: ${postsResult.exceptionOrNull()?.message}"
            }
        } catch (e: Exception) {
            errorMessage = "加载失败: ${e.message}"
        } finally {
            isLoading = false
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("帖子详情") },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "返回")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color(0xFF4361EE),
                    titleContentColor = Color.White,
                    navigationIconContentColor = Color.White
                )
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
        // 加载状态
        if (isLoading) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                CircularProgressIndicator()
            }
        }
        // 错误状态
        else if (errorMessage != null) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        Text(
                            text = errorMessage ?: "未知错误",
                            color = MaterialTheme.colorScheme.error
                        )
                    Spacer(modifier = Modifier.height(16.dp))
                    Button(onClick = {
                        // 重新加载数据
                        isLoading = true
                        errorMessage = null
                    }) {
                            Text("重试")
                    }
                }
            }
        }
        // 正常显示内容
        else if (post != null) {
            Column(
                modifier = Modifier
                        .fillMaxSize()
                    .background(Color(0xFFF5F5F5))
            ) {
                // 帖子内容区域（固定）
                PostDetailContent(
                    post = post!!,
                    comments = comments,
                    showCommentInput = showCommentInput,
                    onLikeClick = { likedPost ->
                        coroutineScope.launch {
                            val currentUserId = UserState.currentUserId
                            if (currentUserId != null) {
                                val result = communityApiService.togglePostLike(currentUserId, likedPost.id)
                                if (result.isSuccess) {
                                    // 更新本地状态
                                    post = likedPost.copy(
                                        isLiked = !likedPost.isLiked,
                                        likeCount = if (likedPost.isLiked) likedPost.likeCount - 1 else likedPost.likeCount + 1
                                    )
                                }
                            }
                        }
                    },
                    onFavoriteClick = { favoritedPost ->
                        coroutineScope.launch {
                            val currentUserId = UserState.currentUserId
                            if (currentUserId != null) {
                                val result = communityApiService.togglePostFavorite(currentUserId, favoritedPost.id)
                                if (result.isSuccess) {
                                    // 更新本地状态
                                    post = favoritedPost.copy(
                                        isFavorited = !favoritedPost.isFavorited,
                                        favoriteCount = if (favoritedPost.isFavorited) favoritedPost.favoriteCount - 1 else favoritedPost.favoriteCount + 1
                                    )
                                }
                            }
                        }
                    },
                    onCommentClick = { 
                        showCommentInput = !showCommentInput
                    }
                )

                // 评论输入框（固定在帖子下方）
                if (showCommentInput) {
                    CommentInputSection(
                        commentText = newComment,
                        onCommentChange = { newComment = it },
                        isSubmitting = isSubmittingComment,
                        onSendComment = {
                            coroutineScope.launch {
                                val currentUserId = UserState.currentUserId
                                if (currentUserId != null && newComment.isNotBlank()) {
                                    isSubmittingComment = true
                                    try {
                                        Log.d("PostDetailScreen", "🔥 开始发送一级评论")
                                        val commentContent = newComment // 保存评论内容
                                        val result = addComment(postId, commentContent, currentUserId)
                                        if (result.success) {
                                            // 清空输入框
                                            newComment = ""
                                            // 🔥 优化：不重新加载所有评论，直接添加新评论到列表
                                            val newCommentObj = Comment(
                                                id = System.currentTimeMillis(), // 使用时间戳作为临时ID
                                                postId = postId.toLong(),
                                                userId = currentUserId,
                                                author = UserState.currentUser?.username ?: "用户",
                                                authorAvatar = UserState.currentUserAvatar, // 🔥 添加当前用户头像
                                                content = commentContent, // 使用保存的评论内容
                                                createdAt = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date()),
                                                parentId = null,
                                                rootId = null,
                                                likeCount = 0,
                                                isLiked = false
                                            )
                                            comments = comments + newCommentObj
                                            // 更新帖子评论数
                                            post = post?.copy(commentCount = post!!.commentCount + 1)
                                            Log.d("PostDetailScreen", "🔥 一级评论发送成功")
                                        } else {
                                            Log.e("PostDetailScreen", "🔥 一级评论发送失败: ${result.message}")
                                        }
                                    } catch (e: Exception) {
                                        Log.e("PostDetailScreen", "🔥 一级评论发送异常: ${e.message}")
                                        // 发送评论失败，保持静默
                                    } finally {
                                        isSubmittingComment = false
                                    }
                                }
                            }
                        }
                    )
                }

                // 评论标题
                Text(
                    text = "评论 (${comments.size})",
                    modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
                    style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold),
                    color = Color(0xFF333333)
                )

                // 评论列表（可滚动）
                LazyColumn(
                    modifier = Modifier.weight(1f),
                    verticalArrangement = Arrangement.spacedBy(0.dp)
                ) {
                    if (comments.isEmpty()) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = 32.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = "暂无评论，快来发表第一条评论吧~",
                                    color = Color.Gray,
                                    style = MaterialTheme.typography.bodyMedium
                                )
                            }
                        }
                    } else {
                        items(comments) { comment ->
                            CommentItem(
                                comment = comment,
                                onReplyClick = { replyComment ->
                                    // 防抖机制 - 防止重复导航
                                    val currentTime = System.currentTimeMillis()
                                    android.util.Log.d("PostDetailScreen", "防抖检查 - currentTime: $currentTime, lastNavigationTime: $lastNavigationTime, 差值: ${currentTime - lastNavigationTime}")
                                    
                                    if (currentTime - lastNavigationTime < 1000) { // 1秒防抖
                                        android.util.Log.d("PostDetailScreen", "防抖：忽略重复点击 - commentId: ${replyComment.id}")
                                        return@CommentItem
                                    }
                                    lastNavigationTime = currentTime
                                    
                                    // 导航到评论详情页面 - 使用 launchSingleTop 防止重复导航
                                    android.util.Log.d("PostDetailScreen", "点击回复按钮 - commentId: ${replyComment.id}, comment.author: ${replyComment.author}")
                                    android.widget.Toast.makeText(context, "点击回复按钮 - ID: ${replyComment.id}", android.widget.Toast.LENGTH_SHORT).show()
                                    // 使用扩展函数防止重复压栈
                                    navController.navigateCommentDetail(replyComment.id)
                                }
                            )
                            Spacer(modifier = Modifier.height(8.dp))
                        }
                    }

                    // 底部空白
                    item {
                        Spacer(modifier = Modifier.height(80.dp))
                    }
                }
                
                // 回复窗口
                selectedComment?.let { comment ->
                    CommentReplyWindow(
                        comment = comment,
                        post = post!!,
                        isVisible = showReplyWindow,
                        onDismiss = {
                            showReplyWindow = false
                            selectedComment = null
                        },
                        coroutineScope = coroutineScope,
                        communityApiService = communityApiService,
                        onReplyAdded = {
                            // 刷新评论列表
                            coroutineScope.launch {
                                val currentUserId = UserState.currentUserId
                                if (currentUserId != null) {
                                    val commentsResult = getCommentsByPostId(postId, currentUserId)
                                    comments = commentsResult
                                }
                            }
                        }
                    )
                }
                }
            }
        }
    }
}

@Composable
fun PostDetailContent(
    post: CommunityPost,
    comments: List<Comment>,
    showCommentInput: Boolean,
    onLikeClick: (CommunityPost) -> Unit,
    onFavoriteClick: (CommunityPost) -> Unit,
    onCommentClick: () -> Unit
) {
    Card(
                modifier = Modifier
                    .fillMaxWidth()
            .padding(16.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            // 用户信息
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.fillMaxWidth()
            ) {
                // 头像 - 优先使用当前用户头像，否则使用帖子作者头像
                val currentUserId = UserState.currentUserId
                val displayAvatar = if (post.userId == currentUserId && UserState.currentUserAvatar != null) {
                    UserState.currentUserAvatar
                } else {
                    post.authorAvatar
                }
                
                if (displayAvatar != null && displayAvatar.isNotEmpty()) {
                    SimpleAvatarImage(
                        avatarUrl = displayAvatar,
                        fallbackName = post.author ?: "未知用户",
                        size = 40.dp
                    )
                } else {
                    DefaultAvatar(
                        name = post.author ?: "未知用户",
                        size = 40.dp
                    )
                }
                
                Spacer(modifier = Modifier.width(12.dp))
                
                // 用户名和时间
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = post.author ?: "匿名用户",
                        style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.SemiBold),
                        color = Color(0xFF333333)
                    )
                    Text(
                        text = post.createdAt ?: "",
                        style = MaterialTheme.typography.bodySmall,
                        color = Color.Gray
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(12.dp))
            
            // 标题
            if (!post.title.isNullOrBlank()) {
                Text(
                    text = post.title,
                    style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold),
                    color = Color(0xFF333333),
                    modifier = Modifier.fillMaxWidth()
                )
                Spacer(modifier = Modifier.height(8.dp))
            }
            
            // 内容
            Text(
                text = post.content ?: "",
                style = MaterialTheme.typography.bodyMedium,
                color = Color(0xFF555555),
                lineHeight = 20.sp,
                modifier = Modifier.fillMaxWidth()
            )
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 互动按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                // 点赞按钮
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.clickable { onLikeClick(post) }
                ) {
                    Icon(
                        imageVector = if (post.isLiked) Icons.Default.ThumbUp else Icons.Default.ThumbUpOffAlt,
                        contentDescription = "点赞",
                        tint = if (post.isLiked) Color(0xFFE91E63) else Color.Gray,
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = post.likeCount.toString(),
                        style = MaterialTheme.typography.bodySmall,
                        color = if (post.isLiked) Color(0xFFE91E63) else Color.Gray
                    )
                }
                
                // 收藏按钮
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.clickable { onFavoriteClick(post) }
                ) {
                    Icon(
                        imageVector = if (post.isFavorited) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
                        contentDescription = "收藏",
                        tint = if (post.isFavorited) Color(0xFFFF9800) else Color.Gray,
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = post.favoriteCount.toString(),
                        style = MaterialTheme.typography.bodySmall,
                        color = if (post.isFavorited) Color(0xFFFF9800) else Color.Gray
                    )
                }
                
                // 评论按钮
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.clickable { onCommentClick() }
                ) {
                    Icon(
                        imageVector = Icons.Default.Comment,
                        contentDescription = "评论",
                        tint = if (showCommentInput) Color(0xFF4361EE) else Color.Gray,
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = comments.size.toString(),
                        style = MaterialTheme.typography.bodySmall,
                        color = if (showCommentInput) Color(0xFF4361EE) else Color.Gray
                    )
                }
            }
        }
    }
}

@Composable
fun CommentInputSection(
    commentText: String,
    onCommentChange: (String) -> Unit,
    isSubmitting: Boolean,
    onSendComment: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Row(
            modifier = Modifier.padding(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            OutlinedTextField(
                value = commentText,
                onValueChange = onCommentChange,
                modifier = Modifier.weight(1f),
                placeholder = { Text("写一条评论...") },
                singleLine = true,
                enabled = !isSubmitting,
                colors = TextFieldDefaults.colors(
                    focusedContainerColor = Color.Transparent,
                    unfocusedContainerColor = Color.Transparent
                )
            )
            
            Spacer(modifier = Modifier.width(8.dp))
            
            IconButton(
                onClick = onSendComment,
                enabled = commentText.isNotBlank() && !isSubmitting
            ) {
                if (isSubmitting) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(20.dp),
                        strokeWidth = 2.dp
                    )
                } else {
                    Icon(
                        imageVector = Icons.AutoMirrored.Default.Send,
                        contentDescription = "发送评论",
                        tint = if (commentText.isNotBlank()) Color(0xFF4361EE) else Color.Gray
                    )
                }
            }
        }
    }
}
